from msilib.schema import ListView

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models import Count
from django.shortcuts import render, get_object_or_404, redirect

# Create your views here.
from django.http import HttpResponse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.generic import View, UpdateView

from apps.forms import NewTopicForm, PostForm
from apps.models import Board, Topic, Post


# def Home(request):
#     boards = Board.objects.all()
#     boards_names = list()
#     for board in boards:
#         boards_names.append(board.name)
#
#     response_html = '<br>'.join(boards_names)
#
#     return HttpResponse(response_html)

def Home(request):
    boards = Board.objects.all()
    return render(request, 'home.html', {'boards': boards})

# class BoardListView(ListView):
#     model = Board
#     template_name = 'home.html'
#     context_object_name = 'boards'

def board_topics(request, pk):
    board = get_object_or_404(Board, pk=pk)
    topics = board.topics.order_by('-last_updated').annotate(replies=Count('posts') - 1)
    return render(request, 'topics.html', {'board': board, 'topics': topics})

# def new_topic(request, pk):
#     board = get_object_or_404(Board, pk=pk)
#     return render(request, 'new_topic.html', {'board': board})


# def new_topic(request, pk):
#     board = get_object_or_404(Board, pk=pk)
#     if request.method == 'POST':
#         subject = request.POST['subject']
#         message = request.POST['message']
#         user = User.objects.first()
#         topic = Topic.objects.create(
#             subject=subject,
#             board=board,
#             starter=user
#         )
#         post = Post.objects.create(
#             message=message,
#             topic=topic,
#             created_by=user
#         )
#         return redirect('board_topics', pk=board.pk)
#     return render(request, 'new_topic.html', {'board': board})


@login_required
def new_topic(request, pk):
    board = get_object_or_404(Board, pk=pk)
    if request.method == 'POST':
        form = NewTopicForm(request.POST)
        if form.is_valid():
            topic = form.save(commit=False)
            topic.board = board
            topic.starter = request.user # <- here
            topic.save()
            Post.objects.create(
                message=form.cleaned_data.get('message'),
                topic=topic,
                created_by=request.user # <- and here
            )
            return redirect('topic_posts', pk=pk, topic_pk=topic.pk) # TODO: redirect to the created topic page
    else:
        form = NewTopicForm()
    return render(request, 'new_topic.html', {'board': board, 'form': form})



def topic_posts(request, pk, topic_pk):
    topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk,)
    topic.views += 1
    topic.save()
    return render(request, 'topic_posts.html', {'topic': topic})


# @login_required
# def reply_topic(request, pk, topic_pk):
#     topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk,)
#     if request.method == 'POST':
#         form = PostForm(request.POST)
#         if form.is_valid():
#             post = form.save(commit=False)
#             post.topic = topic
#             post.created_by = request.user
#             post.save()
#             return redirect('topic_posts', pk=pk, topic_pk=topic_pk)
#     else:
#         form = PostForm()
#     return render(request, 'reply_topic.html', {'topic': topic}, {'form': form})


@login_required
def reply_topic(request, pk, topic_pk):
    topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk)
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.topic = topic
            post.created_by = request.user
            post.save()
            return redirect('topic_posts', pk=pk, topic_pk=topic_pk)
    else:
        form = PostForm()
    return render(request, 'reply_topic.html', {'topic': topic, 'form': form})


def new_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save(commit=False)
            return redirect('post_list')

    else:
        form = PostForm()

    return render(request, 'new_post.html', {'form': form})



class NewPostView(View):
    def post(self, request):
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('post_list')
        return render(request, 'new_post.html', {'form': form})

    def get(self, request):
        form = PostForm()
        return render(request, 'new_post.html', {'form': form})

@method_decorator(login_required, name='dispatch')
class PostUpdateView(UpdateView):
    model = Post
    fields = ['message']
    template_name = 'edit_post.html'
    pk_url_kwarg = 'post_pk'
    context_object_name = 'post'


    def get_queryset(self):
        quertset = super().get_queryset()
        return quertset.filter(created_by=self.request.user)
    def form_valid(self, form):
        post = form.save(commit=False)
        post.updated_by = self.request.user
        post.uodate_at = timezone.now()
        post.save()
        return redirect('topic_posts', pk=post.topic.board.pk, topic_pk=post.topic.pk)

